<template>
	<view class="container-page">
		<u-navbar title="分享" :autoBack="true" leftIconColor="#000000" titleStyle="color:#000000;" :placeholder="true"></u-navbar>
		<!-- 顶部海报区域 -->
		<view class="container-top">
			<swiper class="swiper" circular :indicator-dots="false" :autoplay="true" :interval="5000" style="height: 70vh; border-radius: 20rpx; overflow: hidden;" @change="posterListChange">
				<swiper-item v-for="(item,index) in posterList" :key="index">
					<u-image :src="item.image" :lazy-load="true" width="100%" height="55vh" mode="aspectFill"></u-image>
					<view class="logo-code">
						<view class="logo-box">
							<image src="../../static/logo.png" class="logo"></image>
							<view class="platform-list">
								<image src="../../static/share/apple.png" class="platform"></image>
								<image src="../../static/share/android.png" class="platform"></image>
							</view>
						</view>
						<view class="code-box">
							<!-- <view > -->
								
								<!-- <tki-qrcode
									ref="qrcode"
									:cid="'qrcode-'+index"
									:val="qrform.val"
									:size="qrform.size"
									:unit="qrform.unit"
									:background="qrform.background"
									:foreground="qrform.foreground"
									:pdground="qrform.pdground"
									:lv="qrform.lv"
									:onval="qrform.onval"
									:loadMake="true"
									:usingComponents="qrform.usingComponents"
									:showLoading="qrform.showLoading"
									:loadingText="qrform.loadingText"
									@result="qrCodeReady(index, $event)"
								/> -->
							<!-- </view> -->
							<image :src="qrCodeImages"  class="qrcode-wrap"></image>
							<view class="title">长按识别二维码</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>
		
		<!-- 底部操作按钮 -->
		<view class="container-bottom">
			<view class="handle-item" @click="generatePoster">
				<image src="../../static/share/download.png" class="image"></image>
				<view class="title">保存到相册</view>
			</view>
			<view class="handle-item" @click="copyShareLink">
				<image src="../../static/share/sharelink.png" class="image"></image>
				<view class="title">分享链接</view>
			</view>
		</view>
		
		<!-- 海报预览弹窗 -->
		<u-popup mode="center" :show="showShare" :maskClick="false" :safeAreaInsetBottom="false" bgColor="transparent">
			<image :src="shareImage" class="share-image" @click="previewImg"></image>
			<canvas canvas-id="posterCanvas" class="share-info"></canvas>
			<!-- #ifdef H5 -->
			<view class="popup-title">
				长按图片保存到手机
			</view>
			<!-- #endif -->
			<!-- #ifndef H5 -->
			<view class="popup-title">
				点击图片保存到手机
			</view>
			<!-- #endif -->
			<image class="popup-close" @click="closePopup" src="../../static/common/icon_close.png" />
		</u-popup>
		
	</view>
</template>

<script>
	import { HTTP_REDIRECT_URL } from '@/config/app';
	import tkiQrcode from '@/components/tki-qrcode/tki-qrcode';
	
	export default {
		data() {
			return {
				current: 0,
				userInfo: null,
				posterList: [],
				qrCodeImages: '', // 存储所有二维码图片
				shareImage: '',
				showShare: false,
				qrform: {
					val: '',
					size: 54,
					unit: 'rpx',
					// icon: '../../static/logo.png',
					// iconsize: 5,
					onval: false,
					usingComponents: true,
					showLoading: true,
					loadingText: '二维码生成中',
					background: '#ffffff',
					foreground: '#000000',
					pdground: '#000000',
				}
			};
		},
		components: { tkiQrcode },
		mounted() {
			this.getUserInfo();
		},
		onBackPress() {
			if(this.showShare){
				this.showShare=false
				return true
			}
		},
		methods: {
			// 二维码生成回调
			qrCodeReady(index, data) {
				this.$set(this.qrCodeImages, index, data);
			},
			
			// 获取用户信息
			async getUserInfo() {
				const invite = 'pages/download/download'
				try {
					const res = await this.$Api['user'].getUserInfo();
					this.userInfo = res.data;
					// this.qrform.val = encodeURI(`${HTTP_REDIRECT_URL}/#/invite?parent_user_id=${this.userInfo.id}&num=0001`);
					await this.getShareConfig();
				} catch (error) {
					console.error('获取用户信息失败', error);
					this.$refs.uToast.show({ message: '用户信息获取失败', type: 'error' });
				}
			},
			
			// 预览图片
			previewImg() {
				// #ifndef H5
				uni.previewImage({
					current: this.shareImage,
					urls: [this.shareImage]
				});
				// #endif
			},
			
			closePopup() {
				this.showShare = false;
				this.shareImage = '';
			},
			
			posterListChange(e) {
				this.current = e.detail.current;
			},
			
			// 生成海报
			async generatePoster() {
				let that = this
				// 获取屏幕信息
				const systemInfo = uni.getSystemInfoSync();
				// 获取屏幕高度（单位：px）
				const screenHeight = systemInfo.screenHeight;
				const ctx = uni.createCanvasContext('posterCanvas', this);
				this.showShare = true;
				try {
					ctx.setFillStyle('#ffffff'); // 或者使用 'rgb(255, 255, 255)'
					ctx.fillRect(0, 0, 349, 568); // 根据你的画布大小设置，例如 375x667
					// 获取背景图信息
					// const backgroundRes = await this.getImageInfo('../../static/posterImage.jpg');
					const backgroundRes = await this.getImageInfo(this.posterList[this.current].image);
					ctx.drawImage(backgroundRes.path, 0, 0, 349, 439.74);
					// 获取小程序码图片信息
					// const qrCodeRes = await this.getImageInfo('../../static/qrCodeImage.png');
					const qrCodeRes = await this.getImageInfo(this.qrCodeImages);
					console.log(qrCodeRes,'qrCodeRes');
					ctx.drawImage(qrCodeRes.path, 256, 459.74, 72, 72);
					ctx.setFillStyle('#000000'); // 或者使用 'rgb(255, 255, 255)'
					let title = '长按识别二维码'
					ctx.fillText(title, 257, 545)
					// 获取Logo图片信息
					const logoRes = await this.getImageInfo('../../static/logo.png');
					ctx.drawImage(logoRes.path, 24, 468, 52, 52);
					// 获取android图片信息
					const androidRes = await this.getImageInfo('../../static/share/android.png');
					ctx.drawImage(androidRes.path, 28, 527, 14, 14);
					// 获取apple图片信息
					const appleRes = await this.getImageInfo('../../static/share/apple.png');
					ctx.drawImage(appleRes.path, 58, 527, 14, 14);

					// 绘制完成
					ctx.draw(false, () => {
						// 保存海报到临时文件路径
						uni.canvasToTempFilePath({
							canvasId: 'posterCanvas',
							success: (result) => {
								that.shareImage = result.tempFilePath;
								// #ifdef H5
								that.showShare = true;
								// #endif
								// #ifndef H5
								uni.saveImageToPhotosAlbum({
									filePath: result.tempFilePath,
									success: function() {
										that.$Toast('保存成功')
									}
								})
								// #endif
								console.log('海报生成成功，路径：', result.tempFilePath);
							},
							fail: (err) => {
								console.error('海报生成失败：', err);
							},
						});
					});
				} catch (err) {
					console.error('绘制海报过程中出错：', err);
				}
			},
			// 保存图片到相册
			async saveImageToAlbum(filePath) {
				try {
					await new Promise((resolve, reject) => {
						uni.saveImageToPhotosAlbum({
							filePath,
							success: resolve,
							fail: reject
						});
					});
					this.$refs.uToast.show({ message: '保存成功', type: 'success' });
				} catch (error) {
					console.error('保存图片失败', error);
					// #ifdef MP-WEIXIN
					if (error.errMsg.includes('auth')) {
						this.$refs.uToast.show({ 
							message: '需要相册权限', 
							type: 'error',
							duration: 3000
						});
					}
					// #endif
				}
			},
			
			// 获取图片信息
			getImageInfo(src) {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src,
						success: resolve,
						fail: reject
					});
				});
			},
			
			// 复制分享链接
			copyShareLink() {
				uni.setClipboardData({
					data: this.qrform.val,
					success: () => {
						this.$refs.uToast.show({ message: '复制成功', type: 'success' });
					},
					fail: () => {
						this.$refs.uToast.show({ message: '复制失败', type: 'error' });
					}
				});
			},
			
			// 获取分享配置
			async getShareConfig() {
				try {
					const res = await this.$Api.user.getShareConfig();
					this.posterList = res.data.image;
					this.qrCodeImages = res.data.qrcode;
					this.qrform.val = res.data.url
				} catch (error) {
					console.error('获取分享配置失败', error);
					this.$refs.uToast.show({ message: '获取分享配置失败', type: 'error' });
					
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container-page {
		min-height: 100vh;
		background-color: #f8f8f8;
		
		.container-top {
			margin: 26rpx;
			border-radius: 20rpx;
			
			.logo-code {
				background-color: #ffffff;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 40rpx 42rpx;
				
				.platform-list {
					margin-top: 10rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					
					.platform {
						width: 28rpx;
						height: 28rpx;
					}
				}
				
				.logo {
					width: 104rpx;
					height: 104rpx;
				}
				
				.code-box {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					
					.qrcode-wrap {
						width: 114rpx;
						height: 114rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						
						.tki-qrcode {
							width: 100%;
							height: 100%;
						}
					}
					
					.title {
						font-size: 20rpx;
						color: #323334;
						margin-top: 6rpx;
					}
				}
			}
		}
		
		.container-bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			box-sizing: border-box;
			padding: 20rpx 52rpx;
			height: 198rpx;
			background: #FFFFFF;
			border-radius: 28rpx 28rpx 0rpx 0rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
			box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.05);
			
			.handle-item {
				width: 25%;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				transition: opacity 0.3s;
				
				&.disabled {
					opacity: 0.5;
				}
				
				.image {
					width: 104rpx;
					height: 104rpx;
				}
				
				.title {
					font-size: 24rpx;
					color: #323334;
					margin-top: 20rpx;
				}
			}
		}
		
		.poster-preview {
			position: relative;
			background: transparent;
			display: flex;
			flex-direction: column;
			align-items: center;
			
			.share-image {
				width: 349px;
				height: 568px;
				background-color: #ffffff;
				border-radius: 10rpx;
				overflow: hidden;
				box-shadow: 0 0 30rpx rgba(0,0,0,0.2);
			}
			
			.popup-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #FFFFFF;
				line-height: 32rpx;
				text-align: center;
				margin-top: 28rpx;
				text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.5);
			}
			
			.popup-close {
				width: 80rpx;
				height: 80rpx;
				margin: 40rpx auto 0;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 50%;
				background: rgba(255,255,255,0.2);
				backdrop-filter: blur(10rpx);
			}
		}
	}
	.share-bg {
		position: fixed;
		left: 0;
		top: 0;
		z-index: 99;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.5);
	}


	.share-image {
		position: relative;
		top: 0;
		z-index: 100;
		width: 349px;
		height: 568px;
		background-color: #ffffff;
		border-radius: 10rpx;
		overflow: hidden;
	}

	.share-info {
		position: absolute;
		top: 0;
		width: 349px;
		height: 568px;
		background-color: #ffffff;
		border-radius: 10rpx;
		overflow: hidden;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #FFFFFF;
		line-height: 32rpx;
		text-align: center;
		margin-top: 28rpx;
	}

	.popup-close {
		width: 80rpx;
		height: 80rpx;
		margin: 40rpx auto 0;
		display: flex;
		background-color: #ffffff;
		border-radius: 50%;
		align-items: center;
		justify-content: center;
	}
	/* 隐藏画布 */
	canvas {
		position: absolute;
		left: -9999rpx;
		top: -9999rpx;
		visibility: hidden;
	}
</style>